<template>
  <el-container id="login">
    <el-main>
      <el-row type="flex" justify="center" align="middle" style="height: 100%">
        <ResetPassword v-if="isShowResetPwd" @showlogin="showResetPwd"></ResetPassword>
        <el-col v-else :span="6" class="login-form">
          <h1>四川省智能水务管理系统</h1>
          <el-form :model="userForm" :rules="ruleForm" ref="loginForm">
            <el-form-item prop="userName">
              <el-input
                v-model="userForm.userName"
                prefix-icon="el-icon-user-solid"
                placeholder="请输入手机号码"
              ></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="17">
                <el-form-item prop="passWord">
                  <el-input v-model="userForm.passWord" prefix-icon="el-icon-lock" placeholder="请输入密码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item prop="passWord">
                  <el-button type="promary" plain @click="showResetPwd">找回密码</el-button>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <el-button type="success" style="width: 100%" @click="userLogin('loginForm')">Log In</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script>
import ResetPassword from './../components/ResetPassword.vue'
import { login, getMenu } from '@/config/api.js'
import { createRoutes } from '@/utils/routesUtil.js'
export default {
  name: 'loginView',
  data() {
    return {
      isShowResetPwd: false,
      userForm: {
        userName: '1',
        passWord: '1'
      },
      ruleForm: {
        userName: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        passWord: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    ResetPassword
  },
  methods: {
    showResetPwd() {
      this.isShowResetPwd = !this.isShowResetPwd
    },
    userLogin(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // alert('submit!');
          login({ password: this.userForm.passWord, phone: this.userForm.userName })
            .then(res => {
              // console.log(res)
              if (res.code === 200) {
                this.$message({
                  message: '登录成功',
                  type: 'success'
                })
                // this.data.Authorization //token
                sessionStorage.token = res.data.Authorization
                delete res.data.admin.adminPwd // 删除密码
                sessionStorage.userInfo = JSON.stringify(res.data.admin)
                this.$store.dispatch('token', res.data.Authorization)
                this.$store.dispatch('userInfo', res.data.admin)

                // 继续获取菜单的数据
                getMenu()
                  .then(async res => {
                    console.log('菜单数据', res)
                    if (res.code === 200) {
                      let arr = JSON.parse(JSON.stringify(res.data))
                      await this.menuToTreeMemu(arr)

                      this.$router.push({ path: '/home/site' })
                    } else {
                      this.$message({
                        type: 'error',
                        message: '获取菜单数据失败'
                      })
                    }
                  })
                  .catch(err => {
                    throw new Error(err)
                  })
              } else {
                this.$message({
                  message: '登录失败',
                  type: 'error'
                })
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async menuToTreeMemu(menuArr) {
      console.log('后台返回的menu数据：', JSON.parse(JSON.stringify(menuArr)))
      let newMenuArr = []
      let level1 = [] // 所有1级
      let level2 = [] // 所有2级
      for (let i = 0; i < menuArr.length; i++) {
        if (menuArr[i].menuParent) {
          level2.push(menuArr[i])
        } else {
          level1.push(menuArr[i])
        }
      }
      // console.log(level1)
      // console.log(level2)

      // 合并出可以直接使用得菜单数据、
      level1.forEach(item => {
        item.children = []
        level2.forEach(el => {
          if (item.menuId === el.menuParent) {
            item.children.push(el)
          }
        })
      })
      newMenuArr = level1
      console.log('转换为树形的menu数据', newMenuArr)
      // 动态添加路由
      createRoutes(newMenuArr, this)

      sessionStorage.menu = JSON.stringify(newMenuArr)
      this.$store.dispatch('menu', newMenuArr)
    }
  }
}
</script>

<style scoped>
#login {
  height: 100%;
  background-image: url(@/assets/login-bg.jpg);
  background-size: cover;
  background-position: center;
}

.login-form {
  min-width: 400px;
  height: 300px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 30px;
  border-radius: 3px;
  text-align: center;
}
</style>
